package com.guomei.service.exam.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.exam.domain.Exam;
import com.guomei.bean.exam.vo.ExamPager;
import com.guomei.bean.exam.vo.ExamVo;
import com.guomei.mapper.curse.ExamMapper;
import com.guomei.service.exam.ExamService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 考试服务实现类
 */
@Service
@Slf4j
@Transactional
public class ExamServiceImpl implements ExamService {
    @Resource
    private ExamMapper examMapper;
    @Resource
    private com.guomei.service.curse.UserCourseLearnService userCourseLearnService;
    @Resource
    private com.guomei.service.curse.UserCourseJoinService userCourseJoinService;

    @Override
    public Exam getById(Long id) {
        if (id == null) {
            return null;
        }
        return examMapper.selectById(id);
    }

    @Override
    public List<Exam> getAll() {
        return examMapper.selectAll();
    }

    @Override
    public Result<?> getByCondition(Exam exam) {
        PageHelper.startPage(exam.getPageNum(), exam.getPageSize());
        List<Exam> exams = examMapper.selectByCondition(exam);
        // 封装分页结果到PageData
        PageData<Exam> pageData = new PageData<>();
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(exam.getPageNum());
        pageData.setPageSize(exam.getPageSize());
        return Result.success(pageData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(Exam exam) {
        if (exam == null) {
            return false;
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        exam.setCreatedTime(now);
        exam.setUpdatedTime(now);

        // 设置默认值
        if (exam.getStatus() == null) {
            exam.setStatus((short) 0); // 默认未发布状态
        }
        if (exam.getPrice() == null) {
            exam.setPrice(BigDecimal.ZERO);
        }

        return examMapper.insert(exam) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(List<Exam> exams) {
        if (exams == null || exams.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (Exam exam : exams) {
            // 设置创建和更新时间
            exam.setCreatedTime(now);
            exam.setUpdatedTime(now);

            // 设置默认值
            if (exam.getStatus() == null) {
                exam.setStatus((short) 0);
            }
            if (exam.getPrice() == null) {
                exam.setPrice(BigDecimal.ZERO);
            }
        }

        return examMapper.batchInsert(exams) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(Exam exam) {
        if (exam == null || exam.getId() == null) {
            return false;
        }

        // 更新时间设为当前时间
        exam.setUpdatedTime(LocalDateTime.now());

        return examMapper.updateById(exam) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }
        return examMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemove(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return examMapper.batchDelete(ids) > 0;
    }

    @Override
    public List<Exam> getByCourseId(Long courseId) {
        if (courseId == null) {
            return null;
        }
        return examMapper.selectByCourseId(courseId);
    }

    @Override
    public List<Exam> getByCreatorId(Long creatorId) {
        if (creatorId == null) {
            return null;
        }
        return examMapper.selectByCreatorId(creatorId);
    }

    @Override
    public List<Exam> getByStatus(Short status) {
        if (status == null) {
            return null;
        }
        return examMapper.selectByStatus(status);
    }

    @Override
    public ExamPager getByIdWithQuestions(Long examId) {
        if (examId == null) {
            return null;
        }
        return examMapper.selectByIdWithQuestions(examId);
    }

    @Override
    public List<Exam> getByCourseIds(List<Long> courseIds) {
        if (courseIds == null || courseIds.isEmpty()) {
            return new ArrayList<>();
        }
        return examMapper.selectByCourseIds(courseIds);
    }

    @Override
    public Result<?> getByCourseIdsWithPage(List<Long> courseIds, Integer pageNum, Integer pageSize) {
        if (courseIds == null || courseIds.isEmpty()) {
            PageData<Exam> pageData = new PageData<>();
            pageData.setTotal(0L);
            pageData.setData(new ArrayList<>());
            pageData.setPageNum(pageNum != null ? pageNum : 1);
            pageData.setPageSize(pageSize != null ? pageSize : 10);
            return Result.success(pageData);
        }

        // 设置默认分页参数
        int currentPageNum = pageNum != null && pageNum > 0 ? pageNum : 1;
        int currentPageSize = pageSize != null && pageSize > 0 ? pageSize : 10;

        // 开启分页
        PageHelper.startPage(currentPageNum, currentPageSize);
        List<Exam> exams = examMapper.selectByCourseIds(courseIds);

        // 封装分页结果到PageData
        PageData<Exam> pageData = new PageData<>();
        PageInfo<Exam> pageInfo = new PageInfo<>(exams);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(currentPageNum);
        pageData.setPageSize(currentPageSize);

        return Result.success(pageData);
    }

    @Override
    public Result<?> getUserQualifiedExams(Long userId, Integer pageNum, Integer pageSize) {
        log.info("获取用户可参加的考试: userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize);

        // 参数校验
        if (userId == null) {
            log.warn("用户ID不能为空");
            return Result.fail("用户ID不能为空");
        }

        // 设置默认分页参数
        int currentPageNum = pageNum != null && pageNum > 0 ? pageNum : 1;
        int currentPageSize = pageSize != null && pageSize > 0 ? pageSize : 10;

        try {
            // 1. 根据 userId 查询 UserCourseJoin（获取用户所有学习的课程和进度）
            List<com.guomei.bean.curse.domain.UserCourseJoin> userCourseJoins = 
                userCourseJoinService.listByUserId(userId);
            
            if (userCourseJoins == null || userCourseJoins.isEmpty()) {
                log.info("用户{}没有学习课程记录，返回空列表", userId);
                PageData<ExamVo> pageData = new PageData<>();
                pageData.setTotal(0L);
                pageData.setData(new ArrayList<>());
                pageData.setPageNum(currentPageNum);
                pageData.setPageSize(currentPageSize);
                return Result.success(pageData);
            }

            // 2. 提取所有课程ID
            List<Long> courseIds = new ArrayList<>();
            for (com.guomei.bean.curse.domain.UserCourseJoin join : userCourseJoins) {
                if (join.getCourseId() != null) {
                    courseIds.add(join.getCourseId());
                }
            }

            if (courseIds.isEmpty()) {
                log.info("用户{}没有有效的课程记录，返回空列表", userId);
                PageData<ExamVo> pageData = new PageData<>();
                pageData.setTotal(0L);
                pageData.setData(new ArrayList<>());
                pageData.setPageNum(currentPageNum);
                pageData.setPageSize(currentPageSize);
                return Result.success(pageData);
            }

            log.info("用户{}共学习了{}门课程，课程ID: {}", userId, courseIds.size(), courseIds);

            // 3. 根据课程ID列表查询对应的考试（分页）
            PageHelper.startPage(currentPageNum, currentPageSize);
            List<Exam> exams = examMapper.selectByCourseIds(courseIds);

            if (exams == null || exams.isEmpty()) {
                log.info("这些课程没有关联的考试");
                PageData<ExamVo> pageData = new PageData<>();
                pageData.setTotal(0L);
                pageData.setData(new ArrayList<>());
                pageData.setPageNum(currentPageNum);
                pageData.setPageSize(currentPageSize);
                return Result.success(pageData);
            }

            // 4. 构建 courseId -> UserCourseJoin 的映射，方便快速查找进度
            java.util.Map<Long, com.guomei.bean.curse.domain.UserCourseJoin> courseProgressMap = 
                new java.util.HashMap<>();
            for (com.guomei.bean.curse.domain.UserCourseJoin join : userCourseJoins) {
                courseProgressMap.put(join.getCourseId(), join);
            }

            // 5. 整合 VO，包含课程学习进度
            List<ExamVo> examVos = new ArrayList<>();
            for (Exam exam : exams) {
                ExamVo examVo = new ExamVo();
                examVo.setId(exam.getId());
                examVo.setExamName(exam.getExamName());
                examVo.setCourseId(exam.getCourseId());
                examVo.setCoverImage(exam.getCoverImage());
                examVo.setDescription(exam.getDescription());
                examVo.setExamType(exam.getExamType());
                examVo.setDuration(exam.getDuration());
                examVo.setPrice(exam.getPrice());
                examVo.setStartTime(exam.getStartTime());
                examVo.setEndTime(exam.getEndTime());
                examVo.setStatus(exam.getStatus());
                examVo.setCreatorId(exam.getCreatorId());
                examVo.setCreatedTime(exam.getCreatedTime());
                examVo.setUpdatedTime(exam.getUpdatedTime());

                // 获取该考试对应课程的学习进度
                com.guomei.bean.curse.domain.UserCourseJoin courseJoin = 
                    courseProgressMap.get(exam.getCourseId());
                if (courseJoin != null) {
                    Integer progress = courseJoin.getProgress();
                    examVo.setCourseProgress(progress != null ? progress : 0);
                    // 判断是否可以参加考试（进度达到80%）
                    examVo.setCanJoin(progress != null && progress >= 80);
                } else {
                    examVo.setCourseProgress(0);
                    examVo.setCanJoin(false);
                }

                examVos.add(examVo);
            }

            // 6. 封装分页结果
            PageData<ExamVo> pageData = new PageData<>();
            PageInfo<ExamVo> pageInfo = new PageInfo<>(examVos);
            pageData.setTotal(pageInfo.getTotal());
            pageData.setData(examVos);
            pageData.setPageNum(currentPageNum);
            pageData.setPageSize(currentPageSize);

            log.info("用户{}可查看的考试数量: {}，其中可参加的考试: {}", 
                    userId, examVos.size(), 
                    examVos.stream().filter(ExamVo::isCanJoin).count());
            return Result.success(pageData);

        } catch (Exception e) {
            log.error("获取用户考试信息失败: userId={}", userId, e);
            return Result.fail("获取考试列表失败: " + e.getMessage());
        }
    }
}
